// HomePage3.dart
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:talk/pages/add/x_add_router.dart';
import '../../api/DeApi.dart';
import '../../api/DeviceApi.dart';
import '../../api/OrderApi.dart';
import '../../api/UserApi.dart';
import '../../home/AppLocale.dart';
import '../../res/dimens.dart';
import '../../res/gaps.dart';
import '../../routers/fluro_navigator.dart';
import '../../src/utils/theme_utils.dart';
import '../../src/widgets/click_item.dart';
import '../../tools/widgets/load_image.dart';
import '../../tools/widgets/my_button.dart';
import '../../tools/widgets/popup_window.dart';
import '../../utils/toast_utils.dart';
import '../device/x_device_router.dart';
import '../home/widgets/goods_add_menu.dart';
import '../my/model/UserModel.dart';
import '../my/x_user_router.dart';
import '../sip/call/sip_call.dart';


class HomePage3 extends StatefulWidget {
  const HomePage3({super.key});

  // 添加静态全局key
  static final GlobalKey<_HomePage3State> homeKey = GlobalKey<_HomePage3State>();

  @override
  State<HomePage3> createState() => _HomePage3State();
}

class _HomePage3State extends State<HomePage3> {
  final GlobalKey _addKey = GlobalKey();
  final GlobalKey _bodyKey = GlobalKey();
  final GlobalKey _buttonKey = GlobalKey();
  final OrderApi _orderApi = OrderApi();
  final DeviceApi _deApi = DeviceApi();
  final UserApi _userApi = UserApi();
  List<Map<String, dynamic>> _dataList = [];
  bool _isLoading = true;
  String _errorMessage = '';
  late int _userId;
  late int _deptId;
  UserModel? _UserModel;
  bool _isSipInitialized = false;
  bool _isRegistered = false;
  String _localDeviceModel = "RM-1-1-1-1-1-1";
  String _callDeviceModel = "";

  @override
  void initState() {
    super.initState();
    _getUserData();
  }


  Future<void> _getUserData() async {
    try {
      final response = await _userApi.userData();
      if (response.code == 200) {
        setState(() {
          _UserModel = UserModel.fromJson(response.data);
          if (_UserModel != null) {
            _userId = _UserModel!.userId!;

            // 初始化SIP判断
            // if (_UserModel?.userSwitch != null && _UserModel?.userSwitch != '' && !SIPManage.isInitialized()) {
            //   _initializeSip(_UserModel!.userSwitch!);
            // } else if (SIPManage.isInitialized()) {
            //   Toast.show("单例SIPManage");
            //   setState(() {
            //     _isRegistered = SIPManage().getRegistrationStatus();
            //     _isSipInitialized = true;
            //   });
            // }

            //初始化对讲
            if (_UserModel?.userSwitch != null) {
              print("正在初始化1");
              // initializeSipInHomePage3(context, _UserModel!.userSwitch!);

              // initializeSipInHomePage3(_UserModel!.userSwitch!);
            }


            _fetchData();
          }
        });
      } else {
        Toast.show("获取用户数据home异常");
        setState(() => _isLoading = false);
      }
    } catch (e) {
      AppLocale.text('s_get500');;
      setState(() => _isLoading = false);
    }
  }



  //初始化对讲

  // SIP初始化方法（单例模式）
  // Future<void> _initializeSip(String userSwitch) async {
  //   SIPManage.initialize(userSwitch);
  //   await Future.delayed(const Duration(seconds: 3));
  //   Toast.show("初始化SIPManage完成");
  //   setState(() {
  //     _isSipInitialized = SIPManage.isInitialized();
  //     _isRegistered = SIPManage().getRegistrationStatus();
  //   });
  // }

  // 数据加载方法
  Future<void> _fetchData() async {
    try {
      // 刷新时显示加载状态
      setState(() {
        _isLoading = true;
        _errorMessage = '';
      });

      if (_UserModel?.deptId == null) {
        _handleError("部门ID获取失败，无法加载设备");
        return;
      }

      final response = await _deApi.getDeviceData(_UserModel!.userId!);

      if (response.code == 200) {
        final safeData = _convertToMapList(response.rows);
        setState(() {
          _dataList = safeData;
          _isLoading = false;
        });
        print('数据加载成功，共 ${_dataList.length} 条数据');
      } else {
        _handleError('请求失败：${response.msg ?? '未知错误'}');
      }
    } catch (e) {
      _handleError('获取数据异常: ${e.toString()}');
    }
  }


  // 数据格式转换
  List<Map<String, dynamic>> _convertToMapList(dynamic data) {
    if (data == null) return [];
    if (data is! List) {
      print('警告：数据不是列表类型，类型为 ${data.runtimeType}');
      return [];
    }
    return data.fold<List<Map<String, dynamic>>>([], (result, item) {
      if (item is Map<String, dynamic>) result.add(item);
      else print('警告：忽略非Map类型元素，类型为 ${item.runtimeType}');
      return result;
    });
  }

  // 错误处理方法
  void _handleError(String message) {
    print('错误：$message');
    setState(() {
      _errorMessage = message;
      _isLoading = false;
    });
  }

  // 下拉刷新回调方法
  Future<void> _handleRefresh() async {
    // 下拉刷新时重新加载数据
    if (_UserModel != null) {
      // 已加载用户数据：直接刷新设备数据
      await _fetchData();
    } else {
      // 未加载用户数据：重新执行完整初始化流程
      await _getUserData();
    }
  }

  // 构建SliverAppBar（提取为单独方法，方便复用）
  Widget _buildSliverAppBar(Color? iconColor) {
    return SliverAppBar(
      leadingWidth: 60.0,
      leading: Builder(
        builder: (BuildContext context) {
          return IconButton(
            icon: LoadAssetImage(
              'images/home/home_geren',
              width: 32.0,
              height: 32.0,
              color: iconColor,
            ),
            onPressed: () async {
              if (_UserModel != null) {
                final deviceJson = json.encode(_UserModel!.toJson());
                final encoded = Uri.encodeComponent(deviceJson);
                NavigatorUtils.push(
                  context,
                  '${XUserRouter.userInfoPage}?userId=$_userId&userModel=$encoded',
                );
              } else {
                Toast.show("获取用户信息失败，请重试");
              }
            },
          );
        },
      ),
      expandedHeight: 65,
      backgroundColor: Colors.transparent,
      floating: true,
      snap: true,
      actions: <Widget>[
        IconButton(
          tooltip: '添加设备',
          key: _addKey,
          onPressed: _showAddMenu,
          icon: LoadAssetImage(
            'images/goods/add',
            key: const Key('add'),
            width: 24.0,
            height: 24.0,
            color: iconColor,
          ),
        ),
        const SizedBox(width: 10,)
      ],
    );
  }

  // 构建空数据/错误提示的Sliver组件
  Widget _buildEmptyOrErrorSliver() {
    return SliverFillRemaining(
      child: _buildErrorWidget(),
    );
  }

  // 构建设备列表的Sliver组件
  Widget _buildDeviceListSliver() {
    return SliverList(
      delegate: SliverChildBuilderDelegate((context, index) {
        final value = _dataList[index];

        final line = value["lineStatus"] as int;
        final deviceName = value["deviceName"] as String;
        // final statusText = line == 1 ? '在线' : '离线';
        final statusColor = line == 1 ? Colors.green : Colors.grey;
        final deviceId = value["deviceId"] as int;

        //是否分享
        final isShare = (value["isShare"] as int?) ?? 0;
        final statusText = isShare == 1
            ? (line == 1 ? AppLocale.text('h_zaixianfenxiang') : AppLocale.text('h_lixianfenxiang'))
            : (line == 1 ? AppLocale.text('h_zaixian') : AppLocale.text('h_lixian'));


        return Container(
          margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          child: Card(
            color: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            elevation: 5,
            margin: EdgeInsets.zero,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                InkWell(
                  borderRadius: BorderRadius.circular(12),
                  onTap: () {
                    // if(_isRegistered && _isSipInitialized){
                    //   NavigatorUtils.push(context, '${XDeviceRouter.deviceDetails}'
                    //       '?deviceId=$deviceId&type=$type&sum=4&isSipInitialized=${_isSipInitialized.toString()}&isRegistered=${_isRegistered.toString()}');
                    // }else{
                    //   Toast.show("初始化SIP失败，请稍后再试");
                    // }

                      NavigatorUtils.push(context, '${XDeviceRouter.deviceDetails}'
                          '?deviceId=$deviceId&type=$line&sum=4&isSipInitialized=${_isSipInitialized.toString()}&isRegistered=${_isRegistered.toString()}');


                  },
                  child: Container(
                    height: 180,
                    margin: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(12),
                      child: Image.network(
                        value["devicePho"],
                        fit: BoxFit.cover,
                        width: double.infinity,
                        errorBuilder: (context, error, stackTrace) {
                          return const Center(
                            child: Icon(Icons.image_not_supported, size: 50, color: Colors.grey),
                          );
                        },
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 8),
                  child: Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              deviceName,
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.grey.shade700,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                CircleAvatar(
                                  radius: 6,
                                  backgroundColor: statusColor,
                                ),
                                const SizedBox(width: 8),
                                Text(
                                  statusText,
                                  style: TextStyle(
                                    fontSize: 12,
                                    // fontWeight: FontWeight.bold,
                                    // color: statusColor,
                                    color: Colors.black54,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),



                      //回放及设置
                      Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              // 回放按钮及文字 - 完全紧挨着
                              Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center, // 水平居中对齐
                                children: [
                                  IconButton(
                                    icon: LoadAssetImage(
                                      'images/home/home_huifang2',
                                      width: 28.0,
                                      height: 28.0,
                                    ),
                                    onPressed: () => _handleFavorite(deviceId, line, isShare, deviceName),
                                    padding: EdgeInsets.zero, // 移除所有内边距
                                    constraints: const BoxConstraints(), // 移除默认约束
                                    splashRadius: 24, // 点击水波纹效果半径（可选）
                                  ),
                                  // 完全移除间距控件，直接显示文字
                                  Text(
                                    AppLocale.text('h_huifang'),
                                    style: TextStyle(
                                      fontSize: 11,
                                      color: Colors.grey.shade600,
                                      height: 1.0, // 文字行高设为1，减少文字自身上下间距
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(width: 15), // 两个按钮之间的间距
                              // 设置按钮及文字 - 完全紧挨着
                              Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center, // 水平居中对齐
                                children: [
                                  IconButton(
                                    icon: LoadAssetImage(
                                      'images/home/home_shezhi',
                                      width: 28.0,
                                      height: 28.0,
                                    ),
                                    onPressed: () => _handleAddToCart(deviceId, line, isShare, deviceName),
                                    padding: EdgeInsets.zero, // 移除所有内边距
                                    constraints: const BoxConstraints(), // 移除默认约束
                                    splashRadius: 24, // 点击水波纹效果半径（可选）
                                  ),
                                  // 完全移除间距控件，直接显示文字
                                  Text(
                                    AppLocale.text('h_shezhi'),
                                    style: TextStyle(
                                      fontSize: 11,
                                      color: Colors.grey.shade600,
                                      height: 1.0, // 文字行高设为1，减少文字自身上下间距
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),




                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
        childCount: _dataList.length,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final Color? iconColor = ThemeUtils.getIconColor(context);

    return Scaffold(
      // key: _bodyKey,
      key: HomePage3.homeKey,
      // 核心：添加下拉刷新组件 RefreshIndicator
      body: RefreshIndicator(
        // 下拉刷新回调（必须返回Future）
        onRefresh: _handleRefresh,
        // 刷新指示器颜色（可自定义）
        color: Theme.of(context).primaryColor,
        // 刷新背景颜色
        backgroundColor: Colors.white,
        // 触发刷新的下拉距离（默认40.0）
        displacement: 40.0,
        // 滚动内容区域：统一使用 CustomScrollView 包裹，确保 SliverAppBar 始终显示
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : CustomScrollView(
          // 关键：给滚动组件添加key，确保RefreshIndicator能正确识别
          key: const Key('home_refresh_scroll'),
          // 禁止滚动到顶部时的水波纹效果（可选）
          physics: const AlwaysScrollableScrollPhysics(),
          slivers: [
            // 1. 始终显示 SliverAppBar
            _buildSliverAppBar(iconColor),
            // 2. 根据数据状态显示内容（空数据/错误提示 或 设备列表）
            if (_dataList.isEmpty)
              _buildEmptyOrErrorSliver()
            else
              _buildDeviceListSliver(),
          ],
        ),
      ),
    );
  }

  // 错误/空数据界面（内容部分，不包含AppBar）
  Widget _buildErrorWidget() {
    if (_errorMessage.isNotEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            Text(_errorMessage, style: const TextStyle(fontSize: 16, color: Colors.grey)),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: _fetchData,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    } else {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            LoadAssetImage(
              'images/home/home_wushuju',
              width: 200,
              height: 200,
              fit: BoxFit.contain,
            ),
            MyButton(
              onPressed: (){
                Navigator.pushNamed(context, "/addDevice");
              },
              text: '添加设备',
              minWidth: 130,
              radius: 5,
            ),
          ],
        ),
      );
    }
  }


  // 显示添加设备菜单
  void _showAddMenu() {
    final RenderBox button = _addKey.currentContext!.findRenderObject()! as RenderBox;
    showPopupWindow<void>(
      context: context,
      isShowBg: true,
      offset: Offset(button.size.width - 8.0, -12.0),
      anchor: button,
      child: const GoodsAddMenu(),
    );
  }

  // 回放按钮点击事件
  void _handleFavorite(int deviceId, int type, int isShare, String deviceName) {
    final encodedDeviceName = Uri.encodeComponent(deviceName);
    NavigatorUtils.push(
        context, '${XDeviceRouter.deviceBackPage}'
        '?deviceId=$deviceId&type=$type&isShare=$isShare&deviceName=$encodedDeviceName');
  }

  // 设置按钮点击事件
  void _handleAddToCart(int deviceId, int type, int isShare, String deviceName) {
    final encodedDeviceName = Uri.encodeComponent(deviceName);
    NavigatorUtils.push(
        context, '${XDeviceRouter.deviceSettingPage}'
        '?deviceId=$deviceId&type=$type&isShare=$isShare&deviceName=$encodedDeviceName');
  }




}